import { Space, Button, message } from "antd";
import { useEffect, useState } from "react";
import FlowCanvas from "@/pages/components/flow-canvas/index.jsx";
import {
  PlusOutlined,
  VerticalAlignBottomOutlined,
  SwapOutlined,
  EyeOutlined,
  SaveOutlined,
} from "@ant-design/icons";
import ProjectTree from "@/pages/components/project-tree/index.jsx";
import { useRef } from "react";
import "./index.less";
import { nodeConfigByIcon } from "@/pages/components/flow-canvas/nodes.js";
import { NODE_TYPE_ROOT } from "@/utils/constant.js";
import { findInstanceOrBranchDetail } from "@/api/project-flow.js";
import { CommonTitle } from "@/components";
import ConfigList from "@/pages/base-config/components/config-list/index.jsx";
import ConfigFormContext from "@/pages/base-config/components/configFormContext.js";

export const ProjectManage = () => {
  const projectTreeRef = useRef();

  const stencilPannelList = [
    {
      typeCode: "1",
      templateType: "7",
      templateName: "测试用例",
    },
  ];

  const [currrentTreeItem, setCurrentTreeItem] = useState(null);
  const [flowData, setFlowData] = useState(null);
  const designerRef = useRef(null);

  const projectClick = (project) => {
    setCurrentTreeItem(project);
  };

  const onNewProject = () => {
    projectTreeRef.current.onAddProject();
  };

  const onOpenProject = () => {
    projectTreeRef.current.onOpenProject();
  };

  const [isTool, setIsTool] = useState(false);

  useEffect(() => {
    if (currrentTreeItem && currrentTreeItem.config_type == "6") {
      findInstanceOrBranchDetail({ id: currrentTreeItem.id }).then((res) => {
        if (res.data.instanceContent) {
          res.data.instanceContent = JSON.parse(res.data.instanceContent);
        } else {
          res.data.instanceContent = {
            cells: [],
          };
        }
        res.data.projectId = currrentTreeItem.projectId;
        res.data.canvasType = "3";
        setFlowData(res.data);
      });
    } else {
      setFlowData(null);
    }
  }, [currrentTreeItem]);

  useEffect(() => {
    if (designerRef.current) {
      if (isTool) {
        designerRef.current.carouselRef.current.next();
      } else {
        designerRef.current.carouselRef.current.prev();
      }
    }
  }, [designerRef, isTool]);

  const afterGraphInit = (graph, modelData, callback) => {
    if (modelData.cells.length == 0 && flowData) {
      let node = graph.createNode({
        id: flowData.id,
        x: graph.options.width / 2,
        y: 10,
        ...nodeConfigByIcon(flowData.instanceName, "ks"),
        data: {
          id: flowData.id,
          nodeType: NODE_TYPE_ROOT,
          typeCode: "1",
          templateId: flowData.template_id,
          templateCode: flowData.template_code, // 暂未返回
          templateIcon: "ks",
          templateType: "7",
          templateName: flowData.instanceName,
          typeId: flowData.typeId,
        },
      });
      graph.addNode(node);
      callback && callback();
    }
  };

  const onCaseExport = (node) => {
    // todo
  };

  const menuConifg = {
    menuItems(graph, node) {
      let list = [];
      // if (node && node.data.typeCode == "1") {
      //   list.push({ label: "导出", key: "case-export" });
      // }

      return list;
    },
    menuClick(key, graph, node, point) {
      switch (key) {
        case "case-export":
          onCaseExport(node);
          break;
        default:
          break;
      }
    },
  };

  const headerLeftContent = (
    <div className="flex-row">
      <CommonTitle>{isTool ? "用例工具箱" : "工程"}</CommonTitle>
      <div className="flex-1 flex-row flex-end">
        <Space>
          <Button
            className="icon-btn"
            title="创建工程"
            size="small"
            type="text"
            icon={<PlusOutlined />}
            onClick={onNewProject}
          />
          <Button
            className="icon-btn"
            title="导入工程"
            size="small"
            type="text"
            icon={<VerticalAlignBottomOutlined />}
            onClick={onOpenProject}
          />
          <Button
            className="icon-btn"
            title="切换"
            size="small"
            type="text"
            icon={<SwapOutlined />}
            disabled={!currrentTreeItem || !currrentTreeItem.id}
            onClick={() => setIsTool(!isTool)}
          />
        </Space>
      </div>
    </div>
  );

  const treePanel = (
    <ProjectTree
      ref={projectTreeRef}
      onSelect={projectClick}
      selectItem={currrentTreeItem}
    />
  );

  const configListRef = useRef();

  const createTopCenterPanel = () => {
    if (
      !currrentTreeItem ||
      currrentTreeItem.config_type == "6" ||
      currrentTreeItem.config_type == "0"
    ) {
      return null;
    }
    return (
      <div className="flex-row" style={{ width: "100%" }}>
        <CommonTitle>{currrentTreeItem.name}</CommonTitle>
        <div className="flex-row flex-1 flex-end">
        
          <Space>
            <Button
              className="icon-btn"
              size="small"
              icon={<EyeOutlined />}
              onClick={() => configListRef.current.view()}
            ></Button>
            <Button
              className="icon-btn"
              size="small"
              icon={<SaveOutlined />}
              onClick={() => configListRef.current.save()}
            ></Button>
          </Space>
        </div>
      </div>
    );
  };

  const configFormContextValue = {
    showIcon: false,
  };

  const createContentPanel = () => {
    let project = currrentTreeItem;
    if (!project || project.config_type == "0") {
      return <div className="content-mask"></div>;
    } else if (project.config_type == "6") {
      return null;
    } else {
      const config = {
        typeCode: project.config_type,
        typeName: project.name.replace("配置", ""),
      };
      return (
        <div key={project.config_type} className="content-mask">
          <ConfigFormContext.Provider value={configFormContextValue}>
            <ConfigList
              ref={configListRef}
              projectId={project.projectId}
              config={config}
            />
          </ConfigFormContext.Provider>
        </div>
      );
    }
  };

  return (
    <FlowCanvas
      ref={designerRef}
      menuConifg={menuConifg}
      modelData={flowData}
      stencilPannelList={stencilPannelList}
      toolbar={createTopCenterPanel()}
      treePanel={treePanel}
      contentPanel={createContentPanel()}
      headerLeftContent={headerLeftContent}
      afterGraphInit={afterGraphInit}
      showChildren={true}
    ></FlowCanvas>
  );
};

export default ProjectManage;
